package com.gaohe.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gaohe.common.R;
import com.gaohe.pojo.*;
import com.gaohe.service.*;
import com.gaohe.utils.CodeUtils;
import com.gaohe.utils.RegexUtils;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.regex.RegexUtil;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("user")
@Slf4j
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    RedisTemplate redisTemplate;

    //     分页查询
    @GetMapping("/page")
    public R page(@RequestParam int page, @RequestParam int pageSize, @RequestParam String type, @RequestParam(required = false) String name) {
//        Page是一个ArrayList实现，存储查询结果，PageInfo则包含更多分页信息如导航页码。
//        使用Page还是PageInfo取决于前端需求，通常PageInfo更适合提供详细的分页数据。
        Page<User> page1 = new Page<>(page, pageSize);
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.like(!StringUtils.isEmpty(name), User::getName, name);
        qw.eq(User::getType, type);
        qw.orderByDesc(User::getUpdateTime);
        userService.page(page1, qw);
        return R.success(page1);
    }

    //    添加老师
    @PostMapping("/teacher")
    private R saveTeacher(@RequestBody User user, HttpSession session) {
        user.setType("老师");
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
//        Long user1 = (Long) session.getAttribute("user");
        Long user1 = (Long) redisTemplate.opsForValue().get("auth");
        user.setCreateUser(user1);
        user.setUpdateUser(user1);
        boolean flag = userService.save(user);
        return flag ? R.success("添加成功") : R.error("添加失败");
    }


    //    获取老师信息
    @GetMapping("/teacher/{id}")
    public R getTeacherById(@PathVariable Long id) {
        return R.success(userService.getById(id));
    }

    //    编辑老师信息
    @PutMapping("/teacher")
    private R updateTeacher(@RequestBody User user) {
        user.setUpdateTime(LocalDateTime.now());
        boolean flag = userService.updateById(user);
        return flag ? R.success("修改成功") : R.error("修改失败");
    }

    //    禁用老师/会员账号
    @PutMapping("/status")
    private R changeStatus(@RequestBody User user, HttpSession session) {
        Long user1 = (Long) redisTemplate.opsForValue().get("auth");
//        (Long) session.getAttribute("user")
        user.setUpdateUser(user1);
        LambdaQueryWrapper<User> lw = new LambdaQueryWrapper<>();
        lw.eq(User::getId, user.getId());
        user.setUpdateTime(LocalDateTime.now());
        boolean flag = userService.update(user, lw);
        return flag ? R.success("修改成功") : R.error("修改失败");
    }

    //    查询老师的课程
    @Autowired
    ClassesService classesService;

    @GetMapping("/teacher/classes/{userId}")
    private R getTeacherClasses(@PathVariable Long userId) {
        List<Classes> list = classesService.getTeacherClasses(userId);
        return R.success(list);
    }

    //    获取会员信息
    @GetMapping("/user/{id}")
    public R getUserById(@PathVariable Long id) {
        return R.success(userService.getById(id));
    }

    //    新增会员
    @PostMapping("/user")
    public R saveUser(@RequestBody User user, HttpSession session) {
        user.setType("会员");
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
//        Long user1 = (Long) session.getAttribute("user");
        Long user1 = (Long) redisTemplate.opsForValue().get("auth");
        user.setCreateUser(user1);
        user.setUpdateUser(user1);
        user.setUpdateTime(LocalDateTime.now());
        return userService.save(user) ? R.success("新增成功") : R.error("新增失败");
    }

    //    修改会员信息
    @PutMapping("/student")
    private R updateUser(@RequestBody User user) {
        user.setUpdateTime(LocalDateTime.now());
        boolean flag = userService.updateById(user);
        return flag ? R.success("修改成功") : R.error("修改失败");
    }

    //      查看该会员的所有会员卡
    @Autowired
    UserCardService userCardService;

    @GetMapping("/userCards/{userId}")
    public R getCardByUserId(@PathVariable Long userId) {
        List<UserCard> list = userCardService.getCardByUserId(userId);
        return R.success(list);
    }

    //    为用户添加卡，方法有三个属性值id，name,cardId
    @Autowired
    CardService cardService;

    @PostMapping("/user/saveByCardId/{cardId}")
    public R pickCard(@RequestBody Map<String, String> map, @PathVariable Long cardId) {
//        获取用户id
        Long userId = Long.valueOf(map.get("id"));
//        根据id获取会员卡信息
        Card card = cardService.getById(cardId);
        UserCard userCard = null;
        if (card != null) {
            userCard = new UserCard();
            BeanUtils.copyProperties(card, userCard, "id");
            userCard.setCardId(cardId);
            userCard.setUserId(userId);
            userCard.setPrice(card.getPrice());
            userCard.setCardName(card.getName());
            userCard.setStartDate(LocalDate.now());
            userCard.setEndDate(LocalDate.now().plusDays(card.getDay()));
            System.err.println(userCard);
        }
        return userCardService.save(userCard) ? R.success("选卡成功") : R.error("选卡失败");
    }

//    获取验证码

    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody Map<String, String> map) {
//        1.接受手机号
        String phone = map.get("phone");
//        2.检验手机号格式
        if (!RegexUtils.isPhoneNumber(phone)) {
            return R.error("手机号输入有误");
        }
//        3.获取验证码
        Integer code = CodeUtils.generateValidateCode(4);
        log.info("生成验证码code:", code);
        System.out.println(code);
//        4.将验证码放到redis
        redisTemplate.opsForValue().set(
                "code" + phone,
                code,
                5,
                TimeUnit.MINUTES);
        return R.success("验证码发送成功");
    }

    @PostMapping("/login")
    public R save(@RequestBody Map<String, String> map) {
//        1.接受手机号
        String phone = map.get("phone");

//        2.校验手机号
        if (!RegexUtils.isPhoneNumber(phone)) {
            return R.error("手机号输入有误");
        }

//        3.验证码校验，从redis接受
        String code = map.get("code");
        if (StringUtils.isEmpty(code)) {
            return R.error("请输入验证码");
        }
        Object o = redisTemplate.opsForValue().get("code" + phone);
        if (StringUtils.isEmpty(o)) {
            return R.error("验证码已过期");
        }
        if (!String.valueOf(o).equals(code)) {
            return R.error("验证码输入有误");
        }
//          4.类型非空判断
        String type = map.get("type");
        if (StringUtils.isEmpty("type")) {
            return R.error("请输入类型");
        }
//        5.查询详细信息
        LambdaQueryWrapper<User> lwq = new LambdaQueryWrapper<>();
        lwq.eq(User::getPhone, phone);
        lwq.eq(User::getType, type);
        User user = userService.getOne(lwq);
//        查看用户是老师还是会员
        if (Objects.isNull(user) && type.equals("会员")) {
            user = new User();
            user.setName("会员" + phone);
            user.setCreateUser(2L);
            user.setUpdateUser(2L);
            user.setType("会员");
            user.setUpdateTime(LocalDateTime.now());
            user.setUpdateTime(LocalDateTime.now());
            user.setImage("n");
            user.setStatus(1);
            userService.save(user);

        } else if (Objects.isNull(user) && type.equals("老师")) {
            return R.error("老师为注册，请联系工作人员");
        }
        if (StringUtils.isEmpty(user)) {
            R.error("用户未注册");
        }
//        用户停用查询
        if (user.getStatus() == 0) {
            return R.error("用户账号已被停用");
        }

//        登录成功，将用户id存入redis
        redisTemplate.opsForValue().set("auth" + user.getId(),
                user.getId(),
                30,
                TimeUnit.MINUTES);

//         返回用户信息
        return R.success(user);
    }

//      查询用户id和卡片id
    @GetMapping("getSelectedCard")
    public R getSelectedCard(@RequestParam Long userId, @RequestParam Long cardId) {
        LambdaQueryWrapper<UserCard> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UserCard::getUserId, userId);
        lqw.eq(UserCard::getCardId, cardId);
        UserCard userCard = userCardService.getOne(lqw);
        if (!Objects.isNull(userCard)) {
            System.out.println("已选此卡");
            return R.error("已选此卡");
        } else {
            System.out.println("可以购买");
            return R.success("可以购买");
        }
    }

//  查询老师的总课时
    @Autowired
    UserClassService userClassService;
    @GetMapping("/getTeacherCount/{userId}")
    public R getTeacherCount(@PathVariable Long userId)
    {
        HashMap<String,Long>hashMap = userClassService.getTeacherCount(userId);
        return R.success(hashMap);
    }


}
